/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#ifndef XERN_HTTPCLIENT_HPP
#define XERN_HTTPCLIENT_HPP

#include <map>
#include <deque>
#include <stdexcept>
#include <string>
#include <iostream>

#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>

namespace XernMetaverse
{
    using boost::asio::ip::tcp;

    struct HttpResponse;

    /**
     * Http response handler.
     */
    class HttpResponseHandler
    {
    public:
        virtual void OnHttpResponse(boost::shared_ptr<HttpResponse> response) = 0;
        virtual void OnHttpFailure(const boost::system::error_code &error) = 0;
    };

    /**
     * Http resource request.
     */
    struct HttpRequest
    {
        HttpRequest();

        void StoreRequest(std::ostream &out) const;

        enum Method
        {
            RM_GET = 0,
            RM_POST
        };

        std::string url; // The resource url.
        std::string hostname;
        bool isSecure;
        tcp::endpoint endpoint;
        Method method;
        std::string resource;

        typedef std::multimap<std::string, std::string> AttributesType;
        AttributesType attributes;

        boost::shared_array<unsigned char> postData;
        size_t postDataLen;

        HttpResponseHandler *responseHandler;
    };

    /**
     * Http resource response.
     */
    struct HttpResponse
    {
        // Ok response code.
        static const int ResponseOK = 200;
        static const int ResponseNotFound = 404;

        HttpResponse();

        std::string protocol;
        std::string resource;
        int statusCode;
        std::string statusMessage;

        typedef std::multimap<std::string, std::string> AttributesType;
        AttributesType attributes;

        boost::shared_array<unsigned char> payload;
        size_t payloadLen;
    };

    /**
     * Http exception.
     */
    class HttpException: public std::runtime_error
    {
    public:
        HttpException(const std::string &what)
            : std::runtime_error(what) {}
    };

    /**
     * Http client.
     */
    class HttpClient
    {
    public:
        HttpClient();
        ~HttpClient();

        void Request(boost::shared_ptr<HttpRequest> request);

        void CancelAllRequests();

    private:
        void ClientThread();

        void StartRequest(boost::shared_ptr<HttpRequest> request);
        void BeginNextRequest();

        void OnSentRequest(const boost::system::error_code &error);
        void OnResponseHeaderLine(const boost::system::error_code &error, size_t transferred);
        void OnResponseHeader(const boost::system::error_code &error, size_t transferred);
        void OnResponsePayload(const boost::system::error_code &error, size_t transferred);

        boost::thread clientThread, ioThread;
        boost::mutex clientMutex;
        boost::condition_variable newRequestCondition;
        boost::condition_variable finishRequestCondition;

        boost::shared_ptr<HttpRequest> currentRequest;
        boost::shared_ptr<HttpResponse> currentResponse;
        std::deque<boost::shared_ptr<HttpRequest> > requestQueue;

        boost::asio::io_service ioService;
        tcp::socket socket;
        tcp::endpoint lastEndpoint;

        boost::asio::streambuf requestBuffer;
        boost::asio::streambuf responseBuffer;
    };

}; // namespace Xern

#endif //XERN_HTTPCLIENT_HPP
